{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "eb29d06b-5043-495f-b53c-6cacb651f351",
   "metadata": {},
   "source": [
    "Chapter 08\n",
    "# 用assert检查条件是否为真\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "eaac5622-cf7b-4182-a1d0-5723cf4b264d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义除法函数\n",
    "def divide(a, b):\n",
    "    assert b != 0, \"除数不能为零\"\n",
    "    return a / b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1c21ee84-01f9-481e-af5b-4bf266c7b049",
   "metadata": {},
   "outputs": [
    {
     "ename": "AssertionError",
     "evalue": "除数不能为零",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAssertionError\u001b[0m                            Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[2], line 2\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[38;5;66;03m# 调用自定义函数\u001b[39;00m\n\u001b[1;32m----> 2\u001b[0m result \u001b[38;5;241m=\u001b[39m \u001b[43mdivide\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m10\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m)\u001b[49m\n",
      "Cell \u001b[1;32mIn[1], line 3\u001b[0m, in \u001b[0;36mdivide\u001b[1;34m(a, b)\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mdivide\u001b[39m(a, b):\n\u001b[1;32m----> 3\u001b[0m     \u001b[38;5;28;01massert\u001b[39;00m b \u001b[38;5;241m!=\u001b[39m \u001b[38;5;241m0\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m除数不能为零\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m      4\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m a \u001b[38;5;241m/\u001b[39m b\n",
      "\u001b[1;31mAssertionError\u001b[0m: 除数不能为零"
     ]
    }
   ],
   "source": [
    "# 调用自定义函数\n",
    "result = divide(10, 0)  \n",
    "# 除以零，会引发 AssertionError 异常"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "da12daad-43d2-4b65-8627-781d972df751",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(result)  \n",
    "# 上行不会被执行，因为异常已经引发"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
